package com.youu.youu.manager.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.youu.youu.manager.bean.TPermiss;
import com.youu.youu.manager.bean.TRole;
import com.youu.youu.manager.dao.TPermissMapper;
import com.youu.youu.manager.dao.TRoleMapper;
import com.youu.youu.manager.service.PermissBackstageService;

@Service
public class PermissBackstageServiceImpl implements PermissBackstageService {
	@Autowired
	TPermissMapper tPermissMapper;
	@Autowired
	TRoleMapper tRoleMapper;

	@Override
	public List<TPermiss> getAllPermiss() {
		// 获取所有权限
		List<TPermiss> list = tPermissMapper.select(null);
		// 获取所有父权限
		List<TPermiss> tPermisses = new ArrayList<>();
		Map<Integer, TPermiss> map = new HashMap<>();
		for (TPermiss tPermiss : list) {
			if (tPermiss.getPid() == 0) {
				tPermisses.add(tPermiss);
				map.put(tPermiss.getId(), tPermiss);
			}
		}

		// 给父权限添加子权限
		for (TPermiss tPermiss : list) {
			if (tPermiss.getPid() != 0) {
				TPermiss tPermiss2 = map.get(tPermiss.getPid());
				List<TPermiss> child = tPermiss2.getChild();
				if (child == null) {
					child = new ArrayList<>();
					tPermiss2.setChild(child);
				}
				child.add(tPermiss);
			}
		}

		return tPermisses;
	}

	@Override
	public List<TPermiss> getAllPermissByManager() {
		List<TPermiss> list = tPermissMapper.select(null);
		return list;
	}

	@Override
	public List<TPermiss> getAllPermissByRole(String loginacct) {
		List<TRole> roles = tRoleMapper.selectRoleByManagerIdAlertList(loginacct);
		List<TPermiss> list = tPermissMapper.selectPermissByRoles(roles);
		// 获取所有父权限
		List<TPermiss> tPermisses = new ArrayList<>();
		Map<Integer, TPermiss> map = new HashMap<>();
		for (TPermiss tPermiss : list) {
			if (tPermiss.getPid() == 0) {
				tPermisses.add(tPermiss);
				map.put(tPermiss.getId(), tPermiss);
			}
		}

		// 给父权限添加子权限
		for (TPermiss tPermiss : list) {
			if (tPermiss.getPid() != 0) {
				TPermiss tPermiss2 = map.get(tPermiss.getPid());
				List<TPermiss> child = tPermiss2.getChild();
				if (child == null) {
					child = new ArrayList<>();
					tPermiss2.setChild(child);
				}
				child.add(tPermiss);
			}
		}
		return tPermisses;
	}

	@Override
	public List<TPermiss> getUnProcessAllPermiss() {
		List<TPermiss> list = tPermissMapper.select(null);
		return list;
	}

}
